package com.getpebble.android.core.sync;

import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.SyncResult;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.model.LanguagePackModel;
import com.getpebble.android.common.model.LanguagePackResponse;
import com.getpebble.android.common.model.LockerAppsWrapper;
import com.getpebble.android.framework.firmware.FirmwareManifestSync;
import com.getpebble.android.http.HttpRequestUtil;
import com.getpebble.android.util.SQLUtil;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.koushikdutta.ion.Response;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class PblSyncAdapter extends AbstractThreadedSyncAdapter {
    private static final String TAG = PblSyncAdapter.class.getSimpleName();

    public PblSyncAdapter(Context context, boolean autoInitialize) {
        super(context, autoInitialize);
    }

    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
        Trace.debug(TAG, "onPerformSync start");
        switch (extras.getInt("sync_target", -1)) {
            case R.styleable.WalletFragmentStyle_buyButtonHeight /*0*/:
                syncAll();
                break;
            case SMTPMessage.RETURN_FULL /*1*/:
                syncLockerApps();
                break;
            case ListInfo.INDETERMINATE /*3*/:
                syncFirmwareManifest();
                break;
            case SMTPMessage.NOTIFY_DELAY /*4*/:
                syncLanguages();
                break;
            default:
                Trace.error(TAG, "Unable to derive a proper sync target, not syncing!");
                break;
        }
        Trace.debug(TAG, "onPerformSync stop");
    }

    private void syncAll() {
        syncLockerApps();
        syncFirmwareManifest();
        syncLanguages();
    }

    private void syncLockerApps() {
        Trace.debug(TAG, "syncLockerApps start");
        addAppsToWeb();
        delAppsFromWeb();
        fetchAppsFromWeb();
        Trace.debug(TAG, "syncLockerApps stop");
    }

    private void addAppsToWeb() {
        ExecutionException e;
        InterruptedException e2;
        Trace.debug(TAG, "Adding apps to web");
        String[] selectionArgs = new String[]{"1"};
        Cursor cursor = getContext().getContentResolver().query(PblContentProviderUtil.getTableUri("locker_apps"), null, "_needs_add = ?", selectionArgs, null);
        ArrayList<ContentProviderOperation> operations = new ArrayList();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                try {
                    String addLink = cursor.getString(cursor.getColumnIndex("add_link"));
                    if (TextUtils.isEmpty(addLink)) {
                        Trace.error(TAG, "AddLink missing for app: " + cursor.getString(cursor.getColumnIndex("title")));
                    } else {
                        try {
                            int responseCode = HttpRequestUtil.addAppToLocker(getContext(), addLink, 8000).getHeaders().getResponseCode();
                            if (responseCode != 201) {
                                Trace.error(TAG, "Request failed: " + responseCode);
                            } else {
                                int rowId = cursor.getInt(cursor.getColumnIndex("_id"));
                                ContentValues contentValues = new ContentValues();
                                contentValues.put("_needs_add", Integer.valueOf(0));
                                String[] selectionArgs2 = new String[]{String.valueOf(rowId)};
                                try {
                                    operations.add(ContentProviderOperation.newUpdate(PblContentProviderUtil.getTableUri("locker_apps")).withSelection("_id = ?", selectionArgs2).withValues(contentValues).build());
                                    selectionArgs = selectionArgs2;
                                } catch (ExecutionException e3) {
                                    e = e3;
                                    selectionArgs = selectionArgs2;
                                    Trace.error(TAG, e.getMessage(), e);
                                } catch (InterruptedException e4) {
                                    e2 = e4;
                                    selectionArgs = selectionArgs2;
                                    Trace.error(TAG, e2.getMessage(), e2);
                                }
                            }
                        } catch (TimeoutException e5) {
                            Trace.error(TAG, e5.getMessage(), e5);
                        }
                    }
                } catch (ExecutionException e6) {
                    e = e6;
                    Trace.error(TAG, e.getMessage(), e);
                } catch (InterruptedException e7) {
                    e2 = e7;
                    Trace.error(TAG, e2.getMessage(), e2);
                }
            }
            cursor.close();
        }
        try {
            getContext().getContentResolver().applyBatch("com.getpebble.android.internal.provider", operations);
        } catch (RemoteException e8) {
            Trace.error(TAG, "Failed to update locker apps.", e8);
        } catch (OperationApplicationException e9) {
            Trace.error(TAG, "Failed to update locker apps.", e9);
        }
        Trace.debug(TAG, "Updating locker apps complete!");
    }

    private void delAppsFromWeb() {
        ExecutionException e;
        InterruptedException e2;
        String[] selectionArgs = new String[]{"1"};
        Cursor cursor = getContext().getContentResolver().query(PblContentProviderUtil.getTableUri("locker_apps"), null, "_needs_delete = ?", selectionArgs, null);
        ArrayList<ContentProviderOperation> operations = new ArrayList();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                try {
                    try {
                        int responseCode = HttpRequestUtil.deleteAppFromLocker(getContext(), cursor.getString(cursor.getColumnIndex("remove_link")), 8000).getHeaders().getResponseCode();
                        if (responseCode != 204) {
                            Trace.error(TAG, "Request failed: " + responseCode);
                        } else {
                            String[] selectionArgs2 = new String[]{String.valueOf(cursor.getInt(cursor.getColumnIndex("_id")))};
                            try {
                                operations.add(ContentProviderOperation.newDelete(PblContentProviderUtil.getTableUri("locker_apps")).withSelection("_id = ?", selectionArgs2).build());
                                selectionArgs = selectionArgs2;
                            } catch (ExecutionException e3) {
                                e = e3;
                                selectionArgs = selectionArgs2;
                                Trace.error(TAG, e.getMessage(), e);
                            } catch (InterruptedException e4) {
                                e2 = e4;
                                selectionArgs = selectionArgs2;
                                Trace.error(TAG, e2.getMessage(), e2);
                            }
                        }
                    } catch (TimeoutException e5) {
                        Trace.error(TAG, e5.getMessage(), e5);
                    }
                } catch (ExecutionException e6) {
                    e = e6;
                    Trace.error(TAG, e.getMessage(), e);
                } catch (InterruptedException e7) {
                    e2 = e7;
                    Trace.error(TAG, e2.getMessage(), e2);
                }
            }
            cursor.close();
        }
        try {
            getContext().getContentResolver().applyBatch("com.getpebble.android.internal.provider", operations);
        } catch (RemoteException e8) {
            Trace.error(TAG, "Failed to delete locker apps.", e8);
        } catch (OperationApplicationException e9) {
            Trace.error(TAG, "Failed to delete locker apps.", e9);
        }
        Trace.debug(TAG, "Deleting locker apps complete!");
    }

    private void fetchAppsFromWeb() {
        try {
            synchronizeWebAndLocalApps((JsonObject) HttpRequestUtil.getLockerApps(getContext(), 15000).getResult());
        } catch (ExecutionException e) {
            Trace.error(TAG, e.getMessage(), e);
        } catch (InterruptedException e2) {
            Trace.error(TAG, e2.getMessage(), e2);
        } catch (TimeoutException e3) {
            Trace.error(TAG, e3.getMessage(), e3);
        }
    }

    private void syncLanguages() {
        Trace.debug(TAG, "syncLanguages()");
        try {
            Response<JsonObject> jsonObjectResponse = HttpRequestUtil.fetchLanguages(getContext(), 8000);
            if (jsonObjectResponse == null) {
                try {
                    Trace.warning(TAG, "jsonObjectResponse is null");
                } catch (IllegalArgumentException e) {
                    Trace.warning(TAG, "Failed to marshall language pack manifest; not updating languages", e);
                }
            } else if (jsonObjectResponse.getResult() == null) {
                Trace.warning(TAG, "jsonObjectResponse.getResult() is null");
            } else {
                int numLanguagePacks;
                LanguagePackResponse response = LanguagePackResponse.from(((JsonObject) jsonObjectResponse.getResult()).toString());
                if (response.languagePacks == null) {
                    numLanguagePacks = -1;
                } else {
                    numLanguagePacks = response.languagePacks.length;
                }
                Trace.verbose(TAG, "Received a language pack response of length: " + numLanguagePacks);
                MobileAppBehavior.logLanguagePackResponse(numLanguagePacks);
                LanguagePackModel.removeAll(getContext().getContentResolver());
                ArrayList<ContentProviderOperation> operations = getLanguagePackUpdateOperations(getContext().getContentResolver(), response);
                if (operations.isEmpty()) {
                    Trace.warning(TAG, "No language packs available");
                    return;
                }
                try {
                    getContext().getContentResolver().applyBatch("com.getpebble.android.internal.provider", operations);
                    Trace.verbose(TAG, String.format("Performed %d operations", new Object[]{Integer.valueOf(operations.size())}));
                } catch (RemoteException e2) {
                    Trace.error(TAG, "Failed to update local languages.", e2);
                } catch (OperationApplicationException e3) {
                    Trace.error(TAG, "Failed to update local languages.", e3);
                }
                Trace.debug(TAG, "Updating languages complete.");
            }
        } catch (ExecutionException e4) {
            Trace.error(TAG, "Error fetching language pack manifest", e4);
        } catch (InterruptedException e5) {
            Trace.error(TAG, "Error fetching language pack manifest", e5);
        } catch (TimeoutException e6) {
            Trace.error(TAG, "Error fetching language pack manifest", e6);
        }
    }

    static ArrayList<ContentProviderOperation> getLanguagePackUpdateOperations(ContentResolver contentResolver, LanguagePackResponse response) {
        Set<String> remotes = new HashSet();
        List<ContentValues> rowList = response.toContentValues();
        ArrayList<ContentProviderOperation> operations = new ArrayList();
        for (ContentValues contentValues : rowList) {
            StringBuilder uniqueColumnValues = new StringBuilder();
            for (String column : LanguagePackModel.getUniqueColumns()) {
                uniqueColumnValues.append(contentValues.getAsString(column));
            }
            if (remotes.contains(uniqueColumnValues.toString())) {
                Trace.warning(TAG, "Duplicate: " + uniqueColumnValues.toString());
            } else {
                remotes.add(uniqueColumnValues.toString());
                ContentProviderOperation operation = getInsertOrUpdateOperation(contentResolver, "pebble_language_packs", LanguagePackModel.getUniqueColumns(), contentValues);
                if (operation != null) {
                    Trace.verbose(TAG, "LanguagePackUpdateOperation: " + operation.toString());
                    operations.add(operation);
                } else {
                    Trace.error(TAG, String.format("Operation for %s was null; unique columns: %s", new Object[]{contentValues.toString(), Arrays.toString(LanguagePackModel.getUniqueColumns())}));
                }
            }
        }
        remotes.clear();
        return operations;
    }

    private void synchronizeWebAndLocalApps(JsonObject lockerAppJsonObject) {
        Set<String> remotes = new HashSet();
        LockerAppsWrapper wrapper = (LockerAppsWrapper) new Gson().fromJson((JsonElement) lockerAppJsonObject, LockerAppsWrapper.class);
        if (wrapper == null) {
            Trace.error(TAG, "synchronizeWebAndLocalApps: wrapper is null");
            return;
        }
        List<ContentValues> rowList = wrapper.toContentValues();
        ArrayList<ContentProviderOperation> operations = new ArrayList();
        for (ContentValues contentValues : rowList) {
            String appId = contentValues.getAsString("app_id");
            if (!remotes.contains(appId)) {
                remotes.add(appId);
                ContentProviderOperation operation = getInsertOrUpdateOperation(getContext().getContentResolver(), "locker_apps", new String[]{"app_id"}, contentValues);
                if (operation != null) {
                    operations.add(operation);
                }
            }
        }
        String[] selectionArgs = new String[]{"0"};
        Cursor cursor = getContext().getContentResolver().query(PblContentProviderUtil.getTableUri("locker_apps"), null, "_needs_add = ?", selectionArgs, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                appId = cursor.getString(cursor.getColumnIndex("app_id"));
                if (!(appId == null || remotes.contains(appId))) {
                    operations.add(ContentProviderOperation.newDelete(PblContentProviderUtil.getTableUri("locker_apps")).withSelection("app_id = ? ", new String[]{appId}).build());
                }
            }
            cursor.close();
        }
        remotes.clear();
        try {
            getContext().getContentResolver().applyBatch("com.getpebble.android.internal.provider", operations);
        } catch (RemoteException e) {
            Trace.error(TAG, "Failed to insert locker apps.", e);
        } catch (OperationApplicationException e2) {
            Trace.error(TAG, "Failed to insert locker apps.", e2);
        }
        Trace.debug(TAG, "Inserting locker apps complete!");
    }

    private void syncFirmwareManifest() {
        Trace.debug(TAG, "syncFirmwareManifest start");
        new FirmwareManifestSync(getContext()).syncForAllConnectedDevices();
        Trace.debug(TAG, "syncFirmwareManifest stop");
    }

    private static ContentProviderOperation getInsertOrUpdateOperation(ContentResolver contentResolver, String tableName, String[] selectionColumns, ContentValues contentValues) {
        ContentProviderOperation operation = null;
        String selection = SQLUtil.createSelectionClause(Arrays.asList(selectionColumns));
        String[] selectionArgs = new String[selectionColumns.length];
        for (int i = 0; i < selectionColumns.length; i++) {
            selectionArgs[i] = contentValues.getAsString(selectionColumns[i]);
        }
        Cursor cursor = contentResolver.query(PblContentProviderUtil.getTableUri(tableName), null, selection, selectionArgs, null);
        if (cursor != null) {
            if (cursor.getCount() <= 0 || !cursor.moveToFirst()) {
                operation = ContentProviderOperation.newInsert(PblContentProviderUtil.getTableUri(tableName)).withValues(contentValues).build();
            } else {
                operation = ContentProviderOperation.newUpdate(PblContentProviderUtil.getTableUri(tableName)).withSelection(selection, selectionArgs).withValues(contentValues).build();
            }
            cursor.close();
        } else {
            Trace.verbose(TAG, "Cursor was null; selection: " + selection + " selection args: " + Arrays.toString(selectionArgs));
        }
        return operation;
    }
}
